<?php
namespace app\admin\controller\product;

use app\Request;
use app\admin\controller\AuthController;
use learn\services\UtilService as Util;
use think\facade\Route as Url;


use FormBuilder\Factory\Elm;
use learn\services\FormBuilderService as Form;


//引入模型 
use app\admin\model\product\Loan;
use app\admin\model\product\LoanAttr;
use app\admin\model\system\Map;
use app\models\system\SystemGroupData;


class Product extends AuthController
{

    protected $noNeedLogin = ['index'];

    /**
     * 首页
     */
    public function index ()
    {
        return $this->fetch();
    }

    /**
     * 获取列表
     */
    public function lst ()
    {
        $where = Util::postMore([
            ['page',1],
            ['limit',20],
        ]);
        return app("json")->layui(Loan::systemPage($where));
    }

    /**
     * 修改
     */
    public function edit ($id)
    {
        if (!$id) return app("json")->fail("账号id不能为空");
        $loan = Loan::get($id);
        if (!$loan) return app("json")->fail("没有该账号");
        $form = array();
        $form[] = Elm::input('name','名称',$loan['name'])->col(10);
        $form[] = Elm::frameImage('image','logo',Url::buildUrl('admin/widget.images/index',array('fodder'=>'image','limit'=>1)),$loan['image'])->icon("ios-image")->width('96%')->height('440px');
        $form[] = Elm::select("city","城市",explode(",",$loan['city']))->options(function(){
            $map = Map::where("level_type",1)->select()->toArray();
            $menus=[];
            foreach ($map as $menu) {
                $menus[] = ['value'=>(string)$menu['id'],'label'=>$menu['short_name']];
            }
            return $menus;
        })->filterable(true)->multiple(true)->col(18)->placeholder("城市未选择时,默认为全选");
       
        $form[] = Elm::textarea('info','说明',$loan['info']);
        $form[] = Elm::number('quota','最高额度',$loan['quota']);
        $form[] = Elm::input("url","跳转链接",$loan['url'])->col(10);
        $form[] = Elm::radio('is_page','获客页推荐',$loan['is_page'])->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]]);
        $form[] = Elm::radio('is_show','状态',$loan['is_show'])->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]])->col(10);
        $form = Form::make_post_form($form, url('update',['id'=>$id])->build());
        $this->assign(compact('form'));
        return $this->fetch("public/form-builder");
    }


    //保存修改
    public function update($id)
    {
        $data = Util::postMore([
            ['name',''],
            ['image',''],
            ['info',''],
            ['quota',0],
            ['url',''],
            ['is_page',0],
            ['is_show',1],
            ['city',[]]
        ]);

        if (!empty($data['city'])) {
            if ($data['city'][0] == '') {
                $data['city'] = '0';
            }else{
                $data['city'] = implode(",",$data['city']);
            }
        }else{
            $data['city'] = '0';
        }
        
        if (is_array($data['image'])) $data['image'] = $data['image'][0];
        $data['edit_time'] = time();
        $res = Loan::update($data,['id'=>$id]);
        return $res ? app("json")->success("操作成功",'code') : app("json")->fail("操作失败");
    }

    //创建产品
    public function create()
    {
        $form = array();
        $form[] = Elm::input("name","名称");
        $form[] = Elm::frameImage('image','logo',Url::buildUrl('admin/widget.images/index',array('fodder'=>'image','limit'=>1)))->icon("ios-image")->width('96%')->height('440px');
        $form[] = Elm::select("city","城市")->options(function(){
            $map = Map::where("level_type",1)->select()->toArray();
            $menus=[];
            foreach ($map as $menu) {
                $menus[] = ['value'=>(string)$menu['id'],'label'=>$menu['short_name']];
            }
            return $menus;
        })->filterable(true)->multiple(true)->col(18)->placeholder("城市未选择时,默认为全选");
        $form[] = Elm::textarea('info','说明');
        $form[] = Elm::number('quota','最高额度');
        $form[] = Elm::input("url","跳转链接")->col(10);
        $form[] = Elm::radio('is_page','获客页推荐',1)->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]]);
        $form[] = Elm::radio('is_show','状态',1)->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]])->col(10);
        $form = Form::make_post_form($form, url('save')->build());
        $this->assign(compact('form'));
        return $this->fetch("public/form-builder");
    }

    //保存信息
    public function save()
    {
        $data = Util::postMore([
            ['name',''],
            ['image',''],
            ['info',''],
            ['quota',0],
            ['url',''],
            ['is_page',0],
            ['is_show',1],
            ['city',[]]
        ]);
        
        if (!empty($data['city'])) {
            if ($data['city'][0] == '') {
                $data['city'] = '0';
            }else{
                $data['city'] = implode(",",$data['city']);
            }
        }else{
            $data['city'] = '0';
        }

        if (is_array($data['image'])) $data['image'] = $data['image'][0];
        $data['edit_time'] = time();
        $data['create_time'] = time();
        if($data['name'] == "") return app("json")->fail("产品名称不能为空");
        if($data['quota'] == 0) return app("json")->fail("最高额度必须大于0");
        if($data['url'] == "") return app("json")->fail("跳转链接不能为空");
        return Loan::create($data) ? app("json")->success("操作成功",'code') : app("json")->fail("操作失败");
    }


    //删除
    public function del_product(Request $request)
    {
        $id = $request->param("id",0);
        if ($id == 0) return app("json")->fail("参数有误，Id为空！");
        if (!is_array($id)) $ids = explode(",",$id);
        if ($id == 0) return app("json")->fail("参数有误，Id为空！");
        return Loan::where('id',"in",$id)->delete() ? app("json")->success("操作成功") : app("json")->fail("操作失败");
    }


    public function attr(Request $request)
    {
        $config = getConfig();
        $id = $request->param("id",0);
        if ($id == 0) return app("json")->fail("参数有误，Id为空！");

        $loanattr = LoanAttr::where("loan_id",$id)->find();
        if (empty($loanattr)) {
            $loanattr = [
                'income' => 0,
                'accumulation' => 0,
                'term' => explode(",",''),
                'interest' => explode(",",''),
            ];
        }else{ 
            $loanattr = $loanattr->toArray();
            $loanattr['term'] = explode(",",$loanattr['term']);
            $loanattr['interest'] = explode(",",$loanattr['interest']);
        }
        $this->assign("id",$id);
        $this->assign("loanattr",$loanattr);
        $this->assign("accumulation",$config['accumulation']);      //公积金
        $this->assign("income",$config['income']);
        return $this->fetch();
    }
    public function attrsave(Request $request)
    {
        $data = Util::postMore([
            ['income',0],
            ['accumulation',0],
            ['term',[]],
            ['interest',[]],
            ['loan_id',0],
            ['isincome',0],
            ['isaccumulation',0],
            ['room',0],
            ['isroom',0],
            ['vehicle',0],
            ['isvehicle',0],
            ['policy',0],
            ['ispolicy',0]
        ]);
        if ($data['term']) {
            $data['term'] = implode(",",$data['term']);
        }else{
            $data['term'] = '';
        }
        if ($data['interest']) {
            $data['interest'] = implode(",",$data['interest']);
        }else{
            $data['interest'] = '';
        }
        if (LoanAttr::where('loan_id',$data['loan_id'])->find()) 
        {
            $loanId = $data['loan_id'];
            unset($data['loan_id']);
            LoanAttr::where('loan_id',$loanId)->update($data);
        }else{
            LoanAttr::create($data);
        }



        return app("json")->success($data);
        
    }
}
